package yes;

import com.yes.yll.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/login")
public class Loginserlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("u");
        String password = req.getParameter("p");
        System.out.println("username = "+username);
        System.out.println("password = "+password);
        HttpSession session = req.getSession();
        String sql="SELECT id FROM `user` WHERE `username`=? AND `password`=?";
        Integer id = JdbcUtils.select(sql, Integer.class,username,password);
        if(id !=null && id>0){
            session.setAttribute("UID",id);
            resp.sendRedirect("/yes/index.jsp");
            //跳转到首页
        }
        else{
            resp.sendRedirect("/yes/login.jsp");
        }
        String message=id!=null && id>0?"登录成功":"登录失败";
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(message);
        writer.flush();
        writer.close();
    }

}
